package it.tukano.image;

import java.awt.Dimension;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.imageio.ImageIO;
import org.apache.batik.transcoder.TranscoderException;
import org.apache.batik.transcoder.TranscoderInput;
import org.apache.batik.transcoder.TranscoderOutput;
import org.apache.batik.transcoder.image.PNGTranscoder;

/**
 * Shortcut to generate a BufferedImage from a SVG file using batik
 * @author pgi
 */
public class SvgImageBuilder {

    /**
     * Instance initializer
     */
    public SvgImageBuilder() {
    }

    /**
     * Creates a new buffered image from an svg stream
     * @param svgStream the image source
     * @return the buffered image
     * @throws TranscoderException thrown by batik
     * @throws IOException same
     */
    public BufferedImage create(InputStream svgStream) throws TranscoderException, IOException {
        return create(svgStream, null);
    }
    
    /**
     * Creates a new buffered image from a svg stream with some size
     * @param svgStream the svg source
     * @param size the size of the rendered image
     * @return the buffered image
     * @throws TranscoderException thrown by batik
     * @throws IOException same
     */
    public BufferedImage create(InputStream svgStream, Dimension size) throws TranscoderException, IOException {
        ByteArrayOutputStream pngBuffer = new ByteArrayOutputStream();
        TranscoderOutput transcoderOutput = new TranscoderOutput(pngBuffer);
        PNGTranscoder pngTranscoder = new PNGTranscoder();
        TranscoderInput transcoderInput = new TranscoderInput(svgStream);
        if(size != null) {
            pngTranscoder.addTranscodingHint(PNGTranscoder.KEY_WIDTH, size.width);
            pngTranscoder.addTranscodingHint(PNGTranscoder.KEY_HEIGHT, size.height);
        }
        pngTranscoder.transcode(transcoderInput, transcoderOutput);
        BufferedImage image = ImageIO.read(new ByteArrayInputStream(pngBuffer.toByteArray()));
        return image;
    }
}
